/***************************************************************************
 *   Copyright (C) 2007 by Ivan Vasi?                                      *
 *   ivasic@gmail.com                                                      *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/
#include "mainwindow.h"

#include "globals.h"
#include "log.h"
#include "logobserver.h"
#include "logwidget.h"
#include "menuwidget.h"
#include "centralview.h"
#include "settingswidget.h"
#include "aboutdialog.h"
#include "trackerserver.h"

#include "userdialog.h"
#include "torrentdialog.h"

#include <QtGui>
#include <QtCore>

MainWindow::MainWindow(QWidget* parent, Qt::WFlags fl)
		: QMainWindow(parent, fl), Ui::MainWindow(), m_logWidget(0l), m_menuWidget(0l), m_view(0l)
{
	setupUi(this);

	setupWidgets();

	createActions();
	createSystemTrayIcon();

	setupConnections();
	setupMenu();
	setupToolbar();

	//Prikazi systray ikonu
	m_systray->show();

	//na kraju restore UI
	restoreUIState();
}

MainWindow::~MainWindow()
{
	//sacuvaj state
	saveUIState();
}

void MainWindow::createSystemTrayIcon()
{
	m_systrayMenu = new QMenu(this);
	m_systrayMenu->addAction(minimizeAction);
	m_systrayMenu->addAction(maximizeAction);
	m_systrayMenu->addAction(restoreAction);
	m_systrayMenu->addSeparator();
	m_systrayMenu->addAction(quitAction);

	m_systray = new QSystemTrayIcon(this);
	m_systray->setContextMenu(m_systrayMenu);

	m_systray->setIcon(QIcon(":/images/icons/normal.png"));
}

void MainWindow::createActions()
{
	minimizeAction = new QAction(tr("Mi&nimize"), this);
	connect(minimizeAction, SIGNAL(triggered()), this, SLOT(hide()));

	maximizeAction = new QAction(tr("Ma&ximize"), this);
	connect(maximizeAction, SIGNAL(triggered()), this, SLOT(showMaximized()));

	restoreAction = new QAction(tr("&Restore"), this);
	connect(restoreAction, SIGNAL(triggered()), this, SLOT(show()));

	quitAction = new QAction(QIcon(":/images/icons/exit.png"), tr("&Quit"), this);
	connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));

	newUserAction = new QAction(QIcon(":/images/icons/users.png"), tr("&New user..."), this);
	connect(newUserAction, SIGNAL(triggered()), this, SLOT(showNewUserDialog()));

	newTorrentAction = new QAction(QIcon(":/images/icons/new.png"), tr("&New torrent..."), this);
	connect(newTorrentAction, SIGNAL(triggered()), this, SLOT(showNewTorrentDialog()));

	showAbout = new QAction(QIcon(":/images/icons/normal.png"), tr("&About QTracker"), this);
	connect(showAbout, SIGNAL(triggered()), this, SLOT(showAboutDialog()));

	showSettings = new QAction(QIcon(":/images/icons/settings.png"), tr("&Show settings"), this);
	connect(showSettings, SIGNAL(triggered()), this, SLOT(showSettingsDialog()));
}



void MainWindow::iconActivated(QSystemTrayIcon::ActivationReason reason)
{
	if (reason == QSystemTrayIcon::Trigger)
	{
		if (this->isHidden())
			show();
		else
			hide();
	}
}

void MainWindow::setupConnections()
{
	connect(m_systray, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
			this, SLOT(iconActivated(QSystemTrayIcon::ActivationReason)));

	connect(m_menuWidget, SIGNAL(itemActivated(int)), this, SLOT(onSidebarItemActivated(int)));
	
	connect(Globals::instance().server(), SIGNAL(numConnectionsChanged(int)), m_view, SLOT(numConnectionsChanged(int)));
}

void MainWindow::setupWidgets()
{
	/* LOG WIDGET */
	if (m_logWidget)
		delete m_logWidget;

	m_logWidget = new LogWidget(this);
	m_logWidget->setAllowedAreas(Qt::BottomDockWidgetArea);

	addDockWidget(Qt::BottomDockWidgetArea, m_logWidget);

	/* MENU WIDGET */
	if (m_menuWidget)
		delete m_menuWidget;

	m_menuWidget = new MenuWidget(this);
	m_menuWidget->setAllowedAreas(Qt::LeftDockWidgetArea);

	addDockWidget(Qt::LeftDockWidgetArea, m_menuWidget);
	setupSidebar();

	/* CENTRAL WIDGET */
	if (m_view)
		delete m_view;

	m_view = new CentralView(this);
	setCentralWidget(m_view);
}

void MainWindow::setupMenu()
{
	//File menu
	QMenu* fileMenu = menuBar()->addMenu(tr("&File"));
	fileMenu->addAction(newTorrentAction);
	fileMenu->addAction(newUserAction);
	fileMenu->addAction(quitAction);
	
	QMenu* toolsMenu = menuBar()->addMenu(tr("&Tools"));
	toolsMenu->addAction(showSettings);

	QMenu* helpMenu = menuBar()->addMenu(tr("&Help"));
	helpMenu->addAction(showAbout);
}

void MainWindow::setupToolbar()
{
	m_toolbar = new QToolBar("Main Toolbar", this);
	m_toolbar->setObjectName("main_toolbar");

	m_toolbar->addAction(newTorrentAction);
	m_toolbar->addAction(newUserAction);
	m_toolbar->addAction(showSettings);

	addToolBar(m_toolbar);
}

void MainWindow::setupSidebar()
{
	m_menuWidget->insertItem(QIcon(":/images/icons/new.png"), tr("Show torrents"));
	m_menuWidget->insertItem(QIcon(":/images/icons/users.png"), tr("Show users"));
	m_menuWidget->insertItem(QIcon(":/images/icons/settings.png"), tr("Settings"));
	//m_menuWidget->insertItem(QIcon(":/images/icons/stats.png"), tr("Stats"));
}

void MainWindow::saveUIState()
{
	QSettings* settings = Globals::instance().settings();

	qDebug() << tr("Saving settings to") << settings->fileName();

	settings->beginGroup("gui");
	{
		settings->beginGroup("mainwindow");
		{
			settings->setValue("state", saveState(0x23));
			settings->setValue("visible", isVisible());
			settings->setValue("size", size());
			settings->setValue("position", pos());
		}
		settings->endGroup();
	}
	settings->endGroup();
}

void MainWindow::restoreUIState()
{
	QSettings* settings = Globals::instance().settings();

	//MainWindow
	move(settings->value("gui/mainwindow/position", QPoint(0, 0)).toPoint());
	resize(settings->value("gui/mainwindow/size", QSize(800, 600)).toSize());
	setVisible(settings->value("gui/mainwindow/visible", TRUE).toBool());
	restoreState(settings->value("gui/mainwindow/state", QByteArray()).toByteArray(), 0x23);
}

void MainWindow::showNewUserDialog()
{
	UserDialog dlg(this);
	dlg.exec();

	m_view->refreshCurrentView();
}

void MainWindow::showNewTorrentDialog()
{
	TorrentDialog dlg(this);
	dlg.exec();

	m_view->refreshCurrentView();
}

void MainWindow::onSidebarItemActivated(int item)
{
	switch (item)
	{
		case 0:
			m_view->showTorrents();
			break;
		case 1:
			m_view->showUsers();
			break;
		case 2:
			m_view->showSettings();
			break;
		case 3:
			m_view->showStats();
			break;
	}
}

void MainWindow::showAboutDialog()
{
	AboutDialog dlg(this);
	dlg.exec();
}

void MainWindow::showSettingsDialog()
{
	SettingsWidget* w = new SettingsWidget();
	w->showApplyButton(FALSE);
	
	QPushButton* btnApply = new QPushButton(tr("&Apply"));
	QPushButton* btnClose = new QPushButton(tr("&Close"));
	
	QHBoxLayout* h = new QHBoxLayout();
	h->addSpacing(20);
	h->addWidget(btnApply);
	h->addWidget(btnClose);
	
	QVBoxLayout* l = new QVBoxLayout();
	l->addWidget(w);
	l->addLayout(h);
	
	connect(btnApply, SIGNAL(clicked()), w, SLOT(apply()));
	
	QDialog dlg(this);
	dlg.setLayout(l);
	dlg.setWindowIcon(QIcon(":/images/icons/qtrack.png"));
	dlg.setWindowTitle(tr("QTracker settings"));
	
	connect(btnClose, SIGNAL(clicked()), &dlg, SLOT(reject()));
	
	dlg.exec();
}
